package ph.edu.upd.eee.upcatarchivesearch;

import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
import java.util.regex.Matcher;

/**
 * Created by smartwire on 10/7/2014.
 */
public class SearchResultsActivity extends ListActivity {
    public static final String EXTRA_SEARCH_TERM = "searchterm";

    private ProgressBar pBarSearch;
    private TextView txtHeader;
    private TextView txtDesc;
    private TextView txtProgress;

    @Override
    public void onCreate(Bundle savedStateInstance) {
        super.onCreate(savedStateInstance);

        setContentView(R.layout.activity_searchresults);

        this.pBarSearch = (ProgressBar) findViewById(R.id.pbar_searchresults);
        this.txtHeader = (TextView) findViewById(R.id.txt_searchresults_header);
        this.txtDesc = (TextView) findViewById(R.id.txt_searchresults_description);
        this.txtProgress = (TextView) findViewById(R.id.txt_searchresults_progress);
    }

    @Override
    public void onStart() {
        super.onStart();

        String terms;

        Intent intent;

        intent = getIntent();
        terms = intent.getStringExtra(EXTRA_SEARCH_TERM);
        new Search().execute(terms);
    }

    private class Search extends AsyncTask <String, Integer, ArrayList <SearchResult> > {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            txtProgress.setVisibility(View.VISIBLE);
            pBarSearch.setIndeterminate(true);
            txtProgress.setText(R.string.txt_update_init);
        }

        @Override
        protected ArrayList <SearchResult> doInBackground(String... strings) {
            String searchType;
            String terms, path;
            StringTokenizer javaSs;
            ArrayList<String> arrTerms = new ArrayList <String> ();
            ArrayList <SearchResult> resultSet = new ArrayList <SearchResult> ();
            Matcher mSN, mName;

            SearchArchive searchObj;

            // Initialize variables
            terms = strings[0];
            path = getExternalFilesDir(null) + Utility.ARCHIVE_DIR;

            // Predict search terms
            searchObj = new SearchArchive();
            searchType = searchObj.getTermType(terms);

            if(searchType.equals(SearchArchive.TERM_SN)) {
                // Probably an SN search
                mSN = searchObj.getSNMatcher();

                // Edit header
                txtHeader.setText("Searching for student number " + mSN.group(1) + "-" + mSN.group(2));

                for(char c = 'A'; c <= 'Z'; c++) {
                    resultSet.addAll(searchObj.readArchiveSN(mSN.group(1) + "-" + mSN.group(2), mSN.group(1), path, c));
                    publishProgress(c - 'A');
                }
            }
            else if(searchType.equals(SearchArchive.TERM_NAME)) {
                // Probably a name search
                // Isolate terms from year hashtag
                mName = searchObj.getNameMatcher();
                terms = terms.substring(0, mName.start()) + terms.substring(mName.end(), terms.length());

                // Edit header
                txtHeader.setText("Searching for keywords " + terms.toUpperCase());

                javaSs = new StringTokenizer(terms);

                while(javaSs.hasMoreTokens()) {
                    arrTerms.add(javaSs.nextToken());
                }

                for(char c = 'A'; c <= 'Z'; c++) {
                    resultSet.addAll(searchObj.readArchiveName(arrTerms, mName.group(1), path, c));
                    publishProgress(c - 'A');
                }
            }

            // Sort by increasing relevance
            Collections.sort(resultSet, Collections.reverseOrder());

            return resultSet;
        }

        @Override
        protected void onProgressUpdate(Integer... integers) {
            int percent;

            pBarSearch.setIndeterminate(false);
            pBarSearch.setMax('Z' - 'A' + 1);
            pBarSearch.setProgress(integers[0]);

            percent = (int) (integers[0] / (double) ('Z' - 'A' + 1) * 100);

            txtProgress.setText("Searched " + integers[0] + " of " + ('Z' - 'A' + 1) + " files (" + percent + "%)...");
        }

        @Override
        protected void onPostExecute(ArrayList <SearchResult> resultSet) {
            super.onPostExecute(resultSet);

            SearchResultsArrayAdapter arrayAdapter;

            arrayAdapter = new SearchResultsArrayAdapter(getApplicationContext(), resultSet);
            setListAdapter(arrayAdapter);

            pBarSearch.setIndeterminate(false);
            pBarSearch.setProgress(100);

            txtDesc.setText(resultSet.size() + " result" + ((resultSet.size() > 1) ? "s" : "") + " found!");
            txtProgress.setVisibility(View.INVISIBLE);
        }
    }
}